<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5之LocalStorage</title>
    <!-- 职责分离 git -->
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div class="wrapper">
        <h2>LOCAL TAPAS</h2>
        <p></p>
        <ul class="plates">
            <li>Loading Tapas...</li>
        </ul>
        <form class="add-items">
            <input type="text" name="item" placeholder="Item Name"
             autofocus required>
            <input type="submit" value="+ Add Item">
        </form>
    </div>
    <script>
        // 1. todolist from + ul 
        // 2. loading 
        // 3. 前端的数据持久化 前端数据库 5M
        const addItems = document.querySelector('.add-items');
        const itemsList = document.querySelector('.plates');
        const items = JSON.parse(localStorage.getItem("items"))||[];

        // 将 todolist 显示到列表
        // es6 参数默认数
        function populateList(plates=[],plateList) {
            // console.log(plates);
            plateList.innerHTML = plates.map((plate,i) => `
                <li>
                    <input type="checkbox" data-index=${i} id="item${i}"
                     ${plate.done?'checked':''}/>
                    <label for="item${i}">${plate.text}</label>
                </li>
            `).join('');
        }

        function addItem(event) {
            event.preventDefault();
            const text = this.querySelector('[name=item]').value.trim();
            // console.log(text);
            const item = {  // 新建未完成的对象
                text,  // es6 对象的省略写法
                done:false
            }
            items.push(item);
            populateList(items,itemsList);
            console.log(items);
            // 将数组 序列化字符串
            console.log(JSON.stringify(items));
            localStorage.setItem('items',JSON.stringify(items));
            this.reset();
        }

        // function init() {
        //     // 取出localstirage
        //     // [] .length > 0
        //     // populateList
        //     const storageItems = 
        //     // JSON.parse 字符串 序列化成数组
        //     JSON.parse(localStorage.getItem("items"));
        //     if(storageItems.length) {
        //         populateList(storageItems,itemsList);
        //     }
        // }

        addItems.addEventListener('submit',addItem);
        // init();
        populateList(items,itemsList);
    </script>
</body>
</html>